<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>饮食记录管理 - 健康食谱管理系统</title>
    <link href="https://lib.baomitu.com/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lib.baomitu.com/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #f8f9fa;
            width: 250px;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
        }
        main {
            margin-left: 250px;
            padding: 48px 15px 15px;
        }
        .nav-link {
            color: #333;
            padding: 0.8rem 1rem;
        }
        .nav-link:hover {
            background-color: #e9ecef;
        }
        .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .nav-link i {
            width: 20px;
            text-align: center;
            margin-right: 10px;
        }
        .table img.user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            object-fit: cover;
        }
        .meal-type {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;
        }
        .meal-type.breakfast {
            background-color: #e3f2fd;
            color: #1976d2;
        }
        .meal-type.lunch {
            background-color: #f3e5f5;
            color: #7b1fa2;
        }
        .meal-type.dinner {
            background-color: #e8f5e9;
            color: #388e3c;
        }
        .meal-type.snack {
            background-color: #fff3e0;
            color: #f57c00;
        }
        .food-list {
            max-width: 300px;
        }
        .search-box {
            margin-bottom: 20px;
        }
        .pagination {
            margin-top: 20px;
            justify-content: center;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
        <a class="navbar-brand col-md-3 col-lg-2 mr-0 px-3" href="#">健康食谱管理系统</a>
        <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-toggle="collapse" data-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="w-100"></div>
        <ul class="navbar-nav px-3">
            <li class="nav-item text-nowrap">
                <a class="nav-link" href="#" onclick="logout()">退出登录</a>
            </li>
        </ul>
    </nav>

    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="sidebar-sticky">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">
                        <i class="fas fa-home"></i>仪表盘
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="users.html">
                        <i class="fas fa-users"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="recipes.html">
                        <i class="fas fa-utensils"></i>食谱管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="foods.html">
                        <i class="fas fa-apple-alt"></i>食物管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="posts.html">
                        <i class="fas fa-comments"></i>帖子管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="sports.html">
                        <i class="fas fa-running"></i>运动记录
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="diets.html">
                        <i class="fas fa-hamburger"></i>饮食记录
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main>
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h2">饮食记录管理</h1>
            </div>

            

            <!-- 饮食记录列表 -->
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>用户</th>
                            <th>日期</th>
                            <th>餐次</th>
                            <th>食物列表</th>
                            <th>总热量(千卡)</th>
                            <th>蛋白质(g)</th>
                            <th>碳水(g)</th>
                            <th>脂肪(g)</th>
                            <th>备注</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="dietRecordList">
                        <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </div>
    </main>

    <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://lib.baomitu.com/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 1;
        let totalPages = 1;
        let searchKeyword = '';

        // 检查登录状态
        function checkLogin() {
            const token = localStorage.getItem('adminToken');
            if (!token) {
                window.location.href = 'login.html';
            }
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            checkLogin();
            loadDietRecords();
        });

        // 加载饮食记录
        async function loadDietRecords(page = 1) {
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch(`/api/admin/diet-records?page=${page}&search=${searchKeyword}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 0) {
                    currentPage = page;
                    totalPages = Math.ceil(result.data.total / 10);
                    renderDietRecordList(result.data.list);
                    setupPagination();
                }
            } catch (error) {
                console.error('加载饮食记录失败:', error);
                document.getElementById('dietRecordList').innerHTML = 
                    '<tr><td colspan="10" class="text-center text-danger">加载失败: ' + error.message + '</td></tr>';
            }
        }

        // 渲染饮食记录列表
        function renderDietRecordList(records) {
            const tbody = document.getElementById('dietRecordList');
            if (!records || records.length === 0) {
                tbody.innerHTML = '<tr><td colspan="10" class="text-center">暂无饮食记录数据</td></tr>';
                return;
            }

            tbody.innerHTML = records.map(record => {
                const mealTypeClass = getMealTypeClass(record.mealType);
                const foodList = record.foods.map(food => food.name).join(', ');
                
                return `
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <img src="${record.user.avatar || '/images/default-avatar.png'}" 
                                     alt="用户头像" 
                                     class="user-avatar me-2">
                                <span>${record.user.nickname}</span>
                            </div>
                        </td>
                        <td>${record.date}</td>
                        <td>
                            <span class="meal-type ${mealTypeClass}">
                                ${record.mealType}
                            </span>
                        </td>
                        <td class="food-list">${foodList}</td>
                        <td>${record.totalCalories}</td>
                        <td>${record.totalProtein}</td>
                        <td>${record.totalCarbs}</td>
                        <td>${record.totalFat}</td>
                        <td>${record.notes || '-'}</td>
                        <td>
                            <button class="btn btn-sm btn-danger" onclick="deleteDietRecord(${record.id})">
                                删除
                            </button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // 获取餐次类型样式
        function getMealTypeClass(mealType) {
            switch (mealType) {
                case '早餐': return 'breakfast';
                case '午餐': return 'lunch';
                case '晚餐': return 'dinner';
                case '加餐': return 'snack';
                default: return '';
            }
        }

        // 设置分页
        function setupPagination() {
            const pagination = document.getElementById('pagination');
            let paginationHtml = '';
            
            // 上一页按钮
            paginationHtml += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadDietRecords(${currentPage - 1})" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `;
            
            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                paginationHtml += `
                    <li class="page-item ${currentPage === i ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="loadDietRecords(${i})">${i}</a>
                    </li>
                `;
            }
            
            // 下一页按钮
            paginationHtml += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadDietRecords(${currentPage + 1})" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `;
            
            pagination.innerHTML = paginationHtml;
        }

        // 搜索饮食记录
        function searchDietRecords() {
            searchKeyword = document.getElementById('searchInput').value.trim();
            loadDietRecords(1);
        }

        // 删除饮食记录
        async function deleteDietRecord(id) {
            if (!confirm('确定要删除这条饮食记录吗？')) {
                return;
            }

            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch(`/api/admin/diet-records/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 0) {
                    alert('删除成功');
                    loadDietRecords(currentPage);
                } else {
                    alert('删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除饮食记录失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('adminToken');
            window.location.href = 'login.html';
        }

        // 监听搜索框回车事件
        document.getElementById('searchInput').addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                searchDietRecords();
            }
        });
    </script>
</body>
</html> 